/*
题目：链表两数相加Ⅱ
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外，这两个数字都不会以零开头。
 */
public class AddTwoNumbersⅡ {
    public ListNode reverseLink(ListNode head) {
        ListNode prev = null;
        ListNode cur =head;
        while (cur != null) {
            ListNode front = cur.next;
            cur.next = prev;
            prev = cur;
            cur = front;
        }
        return prev;
    }
    public ListNode addTwoNumbers(ListNode list1, ListNode list2) {
        list1 = reverseLink(list1);
        list2 = reverseLink(list2);
        int carry = 0;
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (list1 != null || list2 != null) {
            if (list1 != null) {
                carry += list1.val;
                list1 = list1.next;
            }
            if (list2 != null) {
                carry += list2.val;
                list2 = list2.next;
            }
            ListNode temp = new ListNode(carry % 10);
            head.next = temp;
            head = head.next;
            carry /= 10;
        }
        if (carry != 0) {
            ListNode temp = new ListNode(carry);
            head.next = temp;
        }
        dummy = reverseLink(dummy.next);
        return dummy;
    }
}
